import { ref, watch, onMounted } from 'vue'

/**
 * localStorage 和 sessionStorage 管理工具
 * @param {string} key - 存储键名
 * @param {any} defaultValue - 默认值
 * @param {'local'|'session'} [type='local'] - 存储类型
 * @returns {Object} 包含存储值和操作方法的对象
 */
export function useStorage(key, defaultValue, type = 'local') {
  const storage = type === 'local' ? localStorage : sessionStorage
  const storedValue = ref(defaultValue)

  // 从存储中读取值
  const readFromStorage = () => {
    try {
      const item = storage.getItem(key)
      return item ? JSON.parse(item) : defaultValue
    } catch (error) {
      console.error(`读取 ${key} 失败:`, error)
      return defaultValue
    }
  }

  // 写入值到存储
  const writeToStorage = (value) => {
    try {
      storage.setItem(key, JSON.stringify(value))
    } catch (error) {
      console.error(`写入 ${key} 失败:`, error)
    }
  }

  // 初始化值
  onMounted(() => {
    storedValue.value = readFromStorage()
  })

  // 监听存储变化
  const handleStorageEvent = (event) => {
    if (event.key === key && event.storageArea === storage) {
      storedValue.value = event.newValue ? JSON.parse(event.newValue) : defaultValue
    }
  }

  onMounted(() => {
    window.addEventListener('storage', handleStorageEvent)
  })

  // 监听值变化并自动同步到存储
  watch(storedValue, (newValue) => {
    writeToStorage(newValue)
  }, { deep: true })

  // 移除存储项
  const removeItem = () => {
    storage.removeItem(key)
    storedValue.value = defaultValue
  }

  // 清空所有存储项
  const clearStorage = () => {
    storage.clear()
    storedValue.value = defaultValue
  }

  return {
    value: storedValue,
    removeItem,
    clearStorage
  }
}
